package com.study.ming.studydemo.thd;

/**
 * 本类展示了waite的用法
 */
public class StudyWaite {
    public static void main(String[] args) {
        Object lock = new Object();
        Object wlock = new Object();
        WaitThread w1 = new WaitThread(lock, "s线程1");
        w1.start();
        NotifyThread t2 = new NotifyThread(lock, "n线程1");
        t2.start();
    }
}

class NotifyThread extends Thread {
    private final Object lock;
    private String name;

    @Override
    public void run() {
        synchronized (lock) {
            // 业务逻辑完成了...
            System.out.println(name + "开始执行");
            // 做一些业务逻辑相关的事。。。。
            try {
                System.out.println(name + "休眠3秒");
                Thread.sleep(3000);
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println(name + "结束休眠,唤醒所有");
            lock.notifyAll();
            System.out.println(name + "结束");
        }
    }

    public NotifyThread(Object lock, String name) {
        super();
        this.lock = lock;
        this.name = name;
    }

}

class WaitThread extends Thread {

    private final Object lock;
    private String name;

    @Override
    public void run() {
        try {
            synchronized (lock) {
                long start = System.currentTimeMillis();
                System.out.println(name + "开始执行");
                System.out.println(name + "休眠3秒");
                Thread.sleep(3000);
                System.out.println(name + "结束休眠,开始 waite");
                lock.wait();
                long end = System.currentTimeMillis();
                System.out.println(name + "结束");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public WaitThread(Object lock, String name) {
        super();
        this.lock = lock;
        this.name = name;
    }

}

